package systempen.cmanager;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import android.R.color;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.text.InputType;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class AccountList extends ListActivity {
	private ArrayList<AccountListItem> _arlAccountListItems;
	private float _sumaSvega;
	ListActivity _thisclass;
	public ListView _lv;
	TextView _tvAccountSum;
	float _fAccountTotal;
	String _selectedId;
	String _selectedCodeText;
	TextView _txtDescription;
	static final private int EDIT_DESCRIPTION = 2;
	static final private int DELETE_ACCOUNT = 1;
	static final private int CREATE_ACCOUNT = 3;
	@Override
	public void onCreate(Bundle icicle) { 
		super.onCreate(icicle);
		ThemePicker.onActivityCreateSetTheme(this);
		try {
			setContentView(R.layout.accountlist);
			_tvAccountSum = (TextView)findViewById(R.id.accountSumTotal);
			_txtDescription = (TextView)findViewById(R.id.textDescriptionN);
			_thisclass = this;
			_lv = getListView();
			registerForContextMenu(_lv);
			FillList();
			OnItemClickListener listener = null;
			listener = new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
					//Toast.makeText(getApplicationContext(),"You've got an event:"+Integer.toString(arg2)+"and "+Long.toString(arg3) ,Toast.LENGTH_SHORT).show();
				}
			};

			_lv.setOnItemClickListener(listener);
		}// od try
		catch (Exception ex) {
			Toast.makeText(this, "AccountMain error: " + ex.getMessage(), Toast.LENGTH_LONG).show();
		}
	}

	public void FillList() {
		try { 
			_fAccountTotal = 0;
			_arlAccountListItems = new ArrayList<AccountListItem>();
			_sumaSvega = 0;
			Cursor c;
			String sqlDebug = "select a, description from account";
			util u = new util();
			c = u.getCursor(sqlDebug, _thisclass);
			c.moveToFirst();
			if (c.getCount() > 0) {
				if (c.moveToFirst()) {
					ArrayList<String> strings = new ArrayList<String>();
					AccountListItem item;
					do {
						String mC = c.getString(0);
						strings.add(mC);
						item = new AccountListItem();
						item.setAccount_code(c.getString(0)); 
						item.setAccount_name(c.getString(1));
						String value = util.getAccountSumDefaultPeriod(c.getString(0),getApplicationContext());
						_fAccountTotal = _fAccountTotal + Float.valueOf(Float.valueOf(value).floatValue());
						value = util.customFormat("###,##0.00",Float.valueOf(value).floatValue());
						item.setAccount_sum(value);
						_arlAccountListItems.add(item);
					} while (c.moveToNext());
				}
			}
			c.close();
			u.db.close();
			AccountListAdapter adapter = new AccountListAdapter(this, R.layout.accountlist_row, _arlAccountListItems);
			this.setListAdapter(null);
			this.setListAdapter(adapter);
			_tvAccountSum.setText(util.customFormat("###,##0.00",Float.valueOf(_fAccountTotal).floatValue()));
		} catch (Exception ex) {
			Toast.makeText(this, "Account list error: " + ex.getMessage(), Toast.LENGTH_LONG).show();
		}
	}
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
		try{
			AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
			RelativeLayout ln = ((RelativeLayout) info.targetView);
			View vi =ln.findViewById(R.id.account_code);
			_selectedId = ((TextView)vi).getText().toString();
			vi =ln.findViewById(R.id.account_name);
			_selectedCodeText = ((TextView)vi).getText().toString();

			menu.setHeaderTitle(_selectedCodeText);
			menu.add(0,v.getId(),0,"Delete account");
			menu.add(0,v.getId(),0,"Rename account");
			menu.add(0,v.getId(),0,"Create account");
		}
		catch (Exception ex){
			Toast.makeText(this,"FFS cr context: "+ex.getMessage(), Toast.LENGTH_LONG).show();
		}
	}
	@Override  
	public boolean onContextItemSelected(MenuItem item) {  
		if(item.getTitle()=="Delete account"){
			deleteAccount(_selectedCodeText);
		}  
		else if(item.getTitle()=="Rename account"){
			modifyAccount(_selectedCodeText);
		}  
		else if(item.getTitle()=="Create account"){
			createAccount();
		}  
		else{
			return false;
		}  
		return true;  
	}
	private void createAccount() {
		showDialog(CREATE_ACCOUNT);//ovaj prikazuje dialog a dialog preko globalnih parametara zna sta treba da radi, valjda
	}

	public void deleteAccount(String id){
		showDialog(DELETE_ACCOUNT);//ovaj prikazuje dialog a dialog preko globalnih parametara zna sta treba da radi, valjda
	}
	public void modifyAccount(String id){
		showDialog(EDIT_DESCRIPTION);//ovaj prikazuje dialog a dialog preko globalnih parametara zna sta treba da radi, valjda
	}
	@Override
	protected Dialog onCreateDialog(int id) {
		LayoutInflater li = LayoutInflater.from(this);
		View categoryDetailView = li.inflate(R.layout.dialog_editview, null);
		TextView tw = (TextView)categoryDetailView.findViewById(R.id.categoryEditText);
		AlertDialog.Builder DetailBuilder = new AlertDialog.Builder(this);
		DetailBuilder.setView(categoryDetailView);
		AlertDialog alertDialog = DetailBuilder.create();
		switch (id) {
		case EDIT_DESCRIPTION:
			DetailBuilder.setTitle("Edit Description");
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					AlertDialog categoryDetail = (AlertDialog)dialog;
					TextView et = (TextView)categoryDetail.findViewById(R.id.categoryEditText);
					_selectedCodeText = et.getText().toString();
					util.execSQL("update account set description = \'"+_selectedCodeText+"\' where a = "+ _selectedId, getApplicationContext());
					FillList();
				}
			});
			alertDialog.setButton2("Cancel", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					return;
				}}); 
			return alertDialog;
		case CREATE_ACCOUNT:
			DetailBuilder.setTitle("Create account");
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					AlertDialog categoryDetail = (AlertDialog)dialog;
					TextView et = (TextView)categoryDetail.findViewById(R.id.categoryEditText);
					_selectedCodeText = et.getText().toString();
					String maxaccount = util.getFirstDataString("select ifnull(max(a)+1,1) a from account", getApplicationContext());
					util.execSQL(" insert into account(a, description) values ("+maxaccount+",\'"+_selectedCodeText+"\')", getApplicationContext());
					FillList();
				}
			});
			alertDialog.setButton2("Cancel", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					return;
				}}); 
			return alertDialog;
		case DELETE_ACCOUNT:
			//////////////////////////////scary alert builder dialog
			AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
			alt_bld.setMessage(String.format("Are you sure you want to delete account: %s", _selectedCodeText));
			alt_bld.setCancelable(false);
			alt_bld.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
			// Action for 'Yes' Button
				try{
					String defaultAccount = util.getDefaultAccountCode(getApplicationContext());
					if (_selectedId.equals(defaultAccount))
					{
						Toast.makeText(getApplicationContext(),"Defaul account cannot be deleted." ,Toast.LENGTH_SHORT).show();
					}
					else
					{
						util.execSQL("update log set account = "+defaultAccount+" where account = "+_selectedId, getApplicationContext());
						util.execSQL("delete from account where a = "+_selectedId, getApplicationContext());
						FillList();
					}
				}
				catch(Exception ex)
				{
					util.showDialog(ex.getMessage(),getApplicationContext());
				}
			}
			})
			.setNegativeButton("No", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
			//  Action for 'NO' Button
			dialog.cancel();
			}
			});
			AlertDialog alert = alt_bld.create();
			// Title for AlertDialog
			alert.setTitle("Delete account: "+_selectedCodeText+" ?");
			// Icon for AlertDialog
			alert.setIcon(R.drawable.help);
			//alert.show();
			//////////////////////////////end scary alert builder dialog
			return alert;
		default:
			break; 
		}
		return null;
	}
	@Override
	protected void onPrepareDialog(int id, Dialog dialog) {
		switch (id) {
		case EDIT_DESCRIPTION:
			AlertDialog ad = (AlertDialog)dialog;
			EditText et2 = (EditText)ad.findViewById(R.id.categoryEditText);
			et2.setText(_selectedCodeText);
			break;
		default:
			break;
		}
	}
	public void onNewAccount(View v){
		showDialog(CREATE_ACCOUNT);
	}



}
